let data = {};
let editingId;
let requestUrl;
let lockStatus = ["未锁定", "已锁定"];
let genderArray = ["未知", "男生", "女生"];

/**
 * 删除用户角色
 * @param roleId 角色ID
 */
function deleteRole(roleId) {
    $.messager.confirm("系统提示", "确认删除选中的角色？", function (result) {
        if (result) {
            let rowData = $("#user_list").datagrid("getSelected");

            if (rowData) {
                let userId = rowData.id;

                ajaxPost("/user_role/delete", {
                    roleId: roleId,
                    userId: userId
                }, function (resp) {
                    // 重新加载用户的角色列表
                    $("#role_list").datagrid("reload", {
                        userId: userId
                    });

                    $.messager.show({
                        title: "系统消息",
                        type: "slide",
                        msg: resp.message
                    });
                }, error);
            }
        }
    });
}

$(document).ready(function () {

    $("#roleId").combobox({
        url: "/role/selectList",
        valueField: "id",
        textField: "name",
        width: 150,
        required: true,
        panelHeight: "auto"
    });

    $("#save").linkbutton({
        iconCls: "icon-save",
        text: "保存"
    }).on("click", function () {
        let rowData = $("#user_list").datagrid("getSelected");

        if (rowData) {
            // 验证表单
            let result = $("#distribute_form").form("validate");

            if (result) {
                let userId = rowData.id;
                let roleId = $("#roleId").combobox("getValue");

                ajaxPost("/user_role/insert", {
                    userId: userId,
                    roleId: roleId
                }, function (resp) {
                    $.messager.show({
                        title: "系统消息",
                        type: "slide",
                        msg: resp.message
                    });

                    // 清空表单
                    $("#distribute_form").form("clear");

                    // 重新加载用户的角色列表
                    $("#role_list").datagrid("reload", {
                        userId: userId
                    });
                }, error);
            } else {
                $.messager.alert("系统提示", "请输入正确的表单项~", "warning");
            }
        }
    });

    $("#cancel").linkbutton({
        iconCls: "icon-cancel",
        text: "取消"
    }).on("click", function () {
        // 清空表单
        $("#distribute_form").form("clear");
    });

    $("#role_list").datagrid({
        url: "/user_role/selectByUserId",
        width: 600,
        height: 400,
        striped: true,
        rownumbers: true,
        fitColumns: true,
        singleSelect: true,
        columns: [[
            {field: "id", title: "角色ID", hidden: true},
            {field: "name", title: "角色名", width: 100, align: "center"},
            {field: "sort", title: "排序", width: 100, align: "center"},
            {field: "description", title: "角色说明", width: 200, align: "center"},
            {field: "serviceId", title: "所属应用", width: 100, align: "center",
                formatter: function (value, rowData, rowIndex) {
                    ajaxGet("/application/selectById", {
                        id: value
                    }, function (resp) {
                        let data = resp.data;

                        $("#application_"+ rowIndex).attr({
                            "src": data.href,
                            "title": data.note
                        }).html(data.name);
                    }, error);

                    return "<a id='application_" + rowIndex + "'></a>";
                }
            },
            {field: "right", title: "操作", align:"center"
                , formatter: function(value, rowData, rowIndex) {
                    return "<a href='javascript:;' onclick='deleteRole(" + rowData.id + ")'>" +
                        "<img title='删除' src='/easyui/themes/icons/delete.png' /></a>";
                }
            }
        ]]
    });

    $("#distribute_dialog").dialog({
        title: "分配权限",
        closable: true,
        closed: true,
        modal: true
    });

    $("#user_list").datagrid({
        url: "/user/selectList",
        height: 600,
        striped: true,
        fitColumns: true,
        rownumbers: true,
        singleSelect: true,
        selectOnCheck: false,
        /**
         * 结束行内编辑事件
         * @param rowIndex 行号
         * @param rowData 行数据
         * @param changes 变更的行数据
         */
        onAfterEdit: function (rowIndex, rowData, changes) {
            data = {
                id: rowData.id,
                name: changes.name ? changes.name : rowData.name,
                phone: changes.phone ? changes.phone : rowData.phone,
                gender: changes.gender ? changes.gender : rowData.gender,
                username: changes.username ? changes.username : rowData.username,
                serviceId: changes.serviceId ? changes.serviceId : rowData.serviceId,
                lockStatus: changes.lockStatus ? changes.lockStatus : rowData.lockStatus
            };
        },
        toolbar: [{
            iconCls: "icon-add",
            text: "添加",
            handler: function() {
                // 添加一行
                $("#user_list").datagrid("appendRow",{
                    id: null,
                    name: null,
                    phone: null,
                    gender: 2,
                    username: null,
                    serviceId: 1,
                    lockStatus: 0
                });

                // 得到表格数据总行数
                let total = $("#user_list").datagrid("getRows").length;

                editingId = total - 1;
                requestUrl = "/user/insert";

                $("#user_list").datagrid("beginEdit", editingId);
            }
        }, "-", {
            iconCls: "icon-edit",
            text: "修改",
            handler: function() {
                let datagrid = $("#user_list");
                let row = datagrid.datagrid("getSelected");

                if (row) {
                    // 获取行的索引，这个索引从0开始
                    let rowIndex = datagrid.datagrid("getRowIndex", row);

                    editingId = rowIndex;
                    requestUrl = "/user/updateById";

                    // 开启行内编辑
                    datagrid.datagrid("beginEdit", rowIndex);
                } else {
                    $.messager.alert("系统提示", "请选择要修改的记录", "warning");
                }
            }
        }, "-", {
            iconCls: "icon-save",
            text: "保存",
            handler: function() {
                if (editingId != null) {
                    // 结束编辑，只有结束编辑才能获取到最新的值
                    $("#user_list").datagrid("endEdit", editingId);

                    ajaxPost(requestUrl, data, function(resp) {
                        $.messager.show({
                            title: "系统消息",
                            type: "slide",
                            msg: resp.message
                        });

                        $("#user_list").datagrid("reload");
                    }, error);

                    editingId = null;
                }
            }
        }, "-", {
            iconCls: "icon-cancel",
            text: "取消",
            handler: function() {
                if (editingId != null) {
                    // 取消编辑
                    $("#user_list").datagrid("cancelEdit", editingId).datagrid("reload");

                    editingId = null;
                }
            }
        }, "-", {
            iconCls: "icon-delete",
            text: "删除",
            handler: function() {
                let rows = $("#user_list").datagrid("getChecked");
                let count = rows.length;

                if (count > 0) {
                    $.messager.confirm("系统提示", "确认删除勾选的" + count + "条数据？", function (bool) {
                        if (bool) {
                            let ids = [];

                            for (let i = 0; i < rows.length; i++) {
                                ids.push(rows[i].id);
                            }

                            ajaxPost("/user/deleteByIds", {
                                ids: JSON.stringify(ids)
                            }, function (resp) {
                                // 重新加载表格数据
                                $("#user_list").datagrid("reload");

                                $.messager.alert("系统提示", resp.message, "info");
                            }, error);
                        }
                    });
                } else {
                    $.messager.alert("系统提示", "请选择要删除的记录！", "warning");
                }
            }
        }, "-", {
            iconCls: "icon-ok",
            text: "分配角色",
            handler: function() {
                let rowData = $("#user_list").datagrid("getSelected");

                if (rowData) {
                    let userId = rowData.id;

                    requestUrl = "/user_role/insert";

                    // 重新加载用户的角色列表
                    $("#role_list").datagrid("reload", {
                        userId: userId
                    });

                    $("#userId").val(userId);

                    $("#distribute_dialog").dialog("open");
                } else {
                    $.messager.alert("系统提示", "请选择一条记录！", "warning");
                }
            }
        }],
        columns: [[
            {field: "ck", checkbox: true},
            {field: "id", title: "用户ID", width: 100, align: "center", editor: "textbox"},
            {field: "name", title: "姓名", width: 100, align: "center", editor: "textbox"},
            {field: "gender", title: "性别", width: 100, align: "center"
                , editor: {
                    type: "combobox",
                    options: {
                        data: getJsonData(genderArray),
                        valueField: "value",
                        textField: "text",
                        panelHeight: "auto"
                    }
                },
                formatter: function (value) {
                    return "<div>" + genderArray[value] + "</div>"
                }
            },
            {field: "username", title: "用户名", width: 100, align: "center", editor: "textbox"},
            {field: "phone", title: "手机号", width: 100, align: "center", editor: "textbox"},
            {field: "lockStatus", title: "锁定状态", width: 100, align: "center",
                editor: {
                    type: "combobox",
                    options: {
                        data: getJsonData(lockStatus),
                        valueField: "value",
                        textField: "text",
                        panelHeight: "auto"
                    }
                },
                formatter: function (value) {
                    return "<div>" + lockStatus[value] + "</div>"
                }
            },
            {field: "serviceId", title: "所属应用", width: 100, align: "center",
                editor: {
                    type: "combobox",
                    options: {
                        url: "/application/selectAll",
                        valueField: "id",
                        textField: "name",
                        panelHeight: "auto"
                    }
                },
                formatter: function (value, rowData, rowIndex) {
                    ajaxGet("/application/selectById", {
                        id: value
                    }, function (resp) {
                        let data = resp.data;

                        $("#service_"+ rowIndex).attr({
                            src: data.href,
                            title: data.note
                        }).html(data.name);
                    }, error);

                    return "<a id='service_" + rowIndex + "'></a>";
                }
            }
        ]]
    });

});